#include "teachingdialog.h"
#include "ui_teachingdialog.h"
#include <QSettings>
#include <QDebug>
#include <QValidator>
#include <QTimer>
#include <QCoreApplication>

#include <QStandardPaths>
#include "serialportmanager.h"
#include "BgaPackageManager.h"
#include "mainwindow.h"
#include <QMessageBox>
#include "bgapackagemanager.h"
#include "BgaImageProcess.h"
#include "toast.h"
TeachingDialog::TeachingDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TeachingDialog)
{
    ui->setupUi(this);
	setModal(false);
	setWindowFlags(Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog);
	
	QStringList list = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Camera");
	QIntValidator* aIntValidator = new QIntValidator;
	ui->lineEditRed->setValidator(aIntValidator);

	int redBrightness = app.value("Red").toInt();
	ui->horizontalSliderRed->setValue(redBrightness);

	SerialPortRx();

	PACKAGE_INFO info = StaticFunction::GetPackageInfo();

	GetLight(LIGHT_RED);
	QTimer::singleShot(150, this, [=]() {
		GetLight(LIGHT_BLUE);
		QTimer::singleShot(150, this, [=]() {
			GetLight(LIGHT_WHITE);
			QTimer::singleShot(150, this, [=]() {
				GetLight(LIGHT_ASSIST);
			});
		});
	});
	
	connect(ui->horizontalSliderRed, SIGNAL(valueChanged(int)), this, SLOT(SliderValueChanged()));
	connect(ui->lineEditRed, SIGNAL(editingFinished()), this, SLOT(EditTextChanged()));
	connect(ui->horizontalSliderBlue, SIGNAL(valueChanged(int)), this, SLOT(SliderValueChanged()));
	connect(ui->lineEditBlue, SIGNAL(editingFinished()), this, SLOT(EditTextChanged()));
	connect(ui->horizontalSliderWhite, SIGNAL(valueChanged(int)), this, SLOT(SliderValueChanged()));
	connect(ui->lineEditWhite, SIGNAL(editingFinished()), this, SLOT(EditTextChanged()));
	connect(ui->horizontalSliderRedAssist, SIGNAL(valueChanged(int)), this, SLOT(SliderValueChanged()));
	connect(ui->lineEditRedAssist, SIGNAL(editingFinished()), this, SLOT(EditTextChanged()));
	
	UpdateWidgets();

	QString str = QString("%1\\Config").arg(appName);
	QString str2 = BgaPackageManager::getInstance()->GetPackageType();

	connect(ui->pushButtonBall, &QPushButton::clicked, [=]() {
		int value1 = ui->horizontalSliderRedAssist->value();
		int value2 = ui->horizontalSliderRed->value();
		int value3 = ui->horizontalSliderBlue->value();
		int value4 = ui->horizontalSliderWhite->value();
		
		QSettings app(QSettings::NativeFormat, QSettings::UserScope, str, str2);
		app.setValue("lightBall1", value1);
		app.setValue("lightBall2", value2);
		app.setValue("lightBall3", value3);
		app.setValue("lightBall4", value4);

		UpdateWidgets();
	});

	/*connect(ui->pushButtonCrossMark, &QPushButton::clicked, [=]() {
		int value1 = ui->horizontalSliderRedAssist->value();
		int value2 = ui->horizontalSliderRed->value();
		int value3 = ui->horizontalSliderBlue->value();
		int value4 = ui->horizontalSliderWhite->value();

		QSettings app(QSettings::NativeFormat, QSettings::UserScope, str, str2);
		app.setValue("lightCM1", value1);
		app.setValue("lightCM2", value2);
		app.setValue("lightCM3", value3);
		app.setValue("lightCM4", value4);
		
		UpdateWidgets();
	});*/

	connect(ui->pushButtonCap, &QPushButton::clicked, [=]() {
		int value1 = ui->horizontalSliderRedAssist->value();
		int value2 = ui->horizontalSliderRed->value();
		int value3 = ui->horizontalSliderBlue->value();
		int value4 = ui->horizontalSliderWhite->value();

		QSettings app(QSettings::NativeFormat, QSettings::UserScope, str, str2);
		app.setValue("lightCap1", value1);
		app.setValue("lightCap2", value2);
		app.setValue("lightCap3", value3);
		app.setValue("lightCap4", value4);
		UpdateWidgets(); 
	});

	connect(ui->pushButtonSubstrate, &QPushButton::clicked, [=]() {
		QSettings app(QSettings::NativeFormat, QSettings::UserScope, str, str2);
		int value1 = ui->horizontalSliderRedAssist->value();
		int value2 = ui->horizontalSliderRed->value();
		int value3 = ui->horizontalSliderBlue->value();
		int value4 = ui->horizontalSliderWhite->value();

		app.setValue("lightSubstrate1", value1);
		app.setValue("lightSubstrate2", value2);
		app.setValue("lightSubstrate3", value3);
		app.setValue("lightSubstrate4", value4);

		UpdateWidgets();
	});

	connect(ui->okButton, &QPushButton::clicked, [=]() {
		close();
	});

	MainWindow *mw = (MainWindow *)this->parentWidget();
	connect(ui->resetButton, &QPushButton::clicked, [=]() {
		QSettings app(QSettings::NativeFormat, QSettings::UserScope, str, str2);
		app.remove("lightSubstrate1");
		app.remove("lightSubstrate2");
		app.remove("lightSubstrate3");
		app.remove("lightSubstrate4");
		app.remove("lightCap1");
		app.remove("lightCap2");
		app.remove("lightCap3");
		app.remove("lightCap4");
		app.remove("lightCM1");
		app.remove("lightCM2");
		app.remove("lightCM3");
		app.remove("lightCM4");
		app.remove("lightBall1");
		app.remove("lightBall2");
		app.remove("lightBall3");
		app.remove("lightBall4");
		UpdateWidgets();
	}); 

	connect(ui->testButton, &QPushButton::clicked, [=]() {
		QSerialPort *m_serialLight = SerialPortManager::getInstance()->GetLightCom();
		disconnect(m_serialLight, &QSerialPort::readyRead, 0, 0);
		ui->testButton->setDisabled(true);
		mw->TeachingTest();
		SerialPortRx();
	}); 

	connect(mw, &MainWindow::TeachingFinishedEvent, this, [=]() {
		ui->testButton->setDisabled(false);
	}, Qt::UniqueConnection);
}

TeachingDialog::~TeachingDialog()
{
    delete ui;
}

void TeachingDialog::UpdateWidgets()
{
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	QString str = QString("Adjust the brightness of the lights to get a clear ball (pad) image.\nCurrent brightness: RedAssist(%1) Red(%2) White(%3) Coaxial(%4)").arg(info.lightConfigBall.brightness1).arg(info.lightConfigBall.brightness2).arg(info.lightConfigBall.brightness3).arg(info.lightConfigBall.brightness4);
	ui->labelBall->setText(str);
	/*str = QString("Adjust the brightness of the lights to get a clear cross mark image.\nCurrent brightness: RedAssist(%1) Red(%2) White(%3) Coaxial(%4)").arg(info.lightConfigCM.brightness1).arg(info.lightConfigCM.brightness2).arg(info.lightConfigCM.brightness3).arg(info.lightConfigBall.brightness4);
	ui->labelCrossMark->setText(str);*/
	str = QString("Adjust the brightness of the lights to get a clear capacitor image.\nCurrent brightness: RedAssist(%1) Red(%2) White(%3) Coaxial(%4)").arg(info.lightConfigCap.brightness1).arg(info.lightConfigCap.brightness2).arg(info.lightConfigCap.brightness3).arg(info.lightConfigCap.brightness4);
	ui->labelCap->setText(str);
	str = QString("Adjust the brightness of the lights to get a clear substrate image.\nCurrent brightness: RedAssist(%1) Red(%2) White(%3) Coaxial(%4)").arg(info.lightConfigSubstrate.brightness1).arg(info.lightConfigSubstrate.brightness2).arg(info.lightConfigSubstrate.brightness3).arg(info.lightConfigSubstrate.brightness4);
	ui->labelSubstrate->setText(str);
}

void TeachingDialog::SerialPortRx()
{
	QSerialPort *m_serialLight = SerialPortManager::getInstance()->GetLightCom();
	connect(m_serialLight, &QSerialPort::readyRead, this, [=]() {
		static QByteArray dataBuffer;
		QByteArray bytes;
		bytes = m_serialLight->readAll();
		//qDebug() << "read:" << bytes;
		for (int i = 0; i < bytes.length(); i++)
		{
			if (bytes[i] == 'A' || bytes[i] == 'B' || bytes[i] == 'C' || bytes[i] == 'D')
			{
				bytes.remove(i, 1);
				i--;
			}
		}
		if (!bytes.isEmpty())
		{
			dataBuffer += bytes;
			//qDebug() << "data:" << dataBuffer;
			if (dataBuffer.length() == 5)
			{
				int value = (dataBuffer[1] - '0') * 1000 + (dataBuffer[2] - '0') * 100 + (dataBuffer[3] - '0') * 10 + (dataBuffer[4] - '0');

				if (dataBuffer[0] == 'b')
				{
					ui->horizontalSliderRed->setValue(value);
					ui->lineEditRed->setText(QString::number(value));
				}
				else if (dataBuffer[0] == 'c')
				{
					ui->horizontalSliderBlue->setValue(value);
					ui->lineEditBlue->setText(QString::number(value));
				}
				else if (dataBuffer[0] == 'd')
				{
					ui->horizontalSliderWhite->setValue(value);
					ui->lineEditWhite->setText(QString::number(value));
				}
				else if (dataBuffer[0] == 'a')
				{
					ui->horizontalSliderRedAssist->setValue(value);
					ui->lineEditRedAssist->setText(QString::number(value));
				}
				dataBuffer.clear();
			}

		}

	});
}

void TeachingDialog::GetLight(LIGHT_TYPE type)
{
	SerialPortManager *sp = SerialPortManager::getInstance();

	if (type == LIGHT_RED)
	{
		sp->GetLightBrightnessB();
	}
	else if (type == LIGHT_BLUE)
	{
		sp->GetLightBrightnessC();
	}
	else if (type == LIGHT_WHITE)
	{
		sp->GetLightBrightnessD();
	}
	else {
		sp->GetLightBrightnessA();
	}

}
void TeachingDialog::SetLight(int light, LIGHT_TYPE type)
{
	SerialPortManager *sp = SerialPortManager::getInstance();
	if (type == LIGHT_RED)
	{
		sp->SetLightBrightnessB(light);
	}
	else if (type == LIGHT_BLUE)
	{
		sp->SetLightBrightnessC(light);
	}
	else if (type == LIGHT_WHITE)
	{
		sp->SetLightBrightnessD(light);
	}
	else {
		sp->SetLightBrightnessA(light);
	}
}

void TeachingDialog::SliderValueChanged()
{
	QSlider *slider = (QSlider *)sender();
	QString name = slider->objectName();
	QString value = QString::number(slider->value());
	if (name == "horizontalSliderRed")
	{
		ui->lineEditRed->setText(value);
		SetLight(slider->value(), LIGHT_RED);
	}
	else if (name == "horizontalSliderBlue")
	{
		ui->lineEditBlue->setText(value);
		SetLight(slider->value(), LIGHT_BLUE);
	}
	else if (name == "horizontalSliderWhite")
	{
		ui->lineEditWhite->setText(value);
		SetLight(slider->value(), LIGHT_WHITE);
	}
	else if (name == "horizontalSliderRedAssist")
	{
		ui->lineEditRedAssist->setText(value);
		SetLight(slider->value(), LIGHT_ASSIST);
	}
}

void TeachingDialog::EditTextChanged()
{
	QLineEdit *edit = (QLineEdit *)sender();

	QString name = edit->objectName();
	int v = edit->text().toInt();
	if (name == "lineEditRed")
	{
		ui->horizontalSliderRed->setValue(v);
		SetLight(v, LIGHT_RED);
	}
	else if (name == "lineEditBlue")
	{
		ui->horizontalSliderBlue->setValue(v);
		SetLight(v, LIGHT_BLUE);
	}
	else if (name == "lineEditWhite")
	{
		ui->horizontalSliderWhite->setValue(v);
		SetLight(v, LIGHT_WHITE);
	}
	else if (name == "lineEditRedAssist")
	{
		ui->horizontalSliderRedAssist->setValue(v);
		SetLight(v, LIGHT_ASSIST);
	}
}

void TeachingDialog::closeEvent(QCloseEvent *)
{
	QSerialPort *m_serialLight = SerialPortManager::getInstance()->GetLightCom();
	disconnect(m_serialLight, &QSerialPort::readyRead, 0, 0);

	MainWindow *mw = (MainWindow *)this->parentWidget();
	disconnect(mw, &MainWindow::TeachingFinishedEvent, 0, 0);
}